package com.bjb.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {

    /**
     * 网络Get请求获取到String类型的返回结果
     * @throws IOException
     * @throws ClientProtocolException
     * @param  url:要请求的url
     */
    public static String NetGetRequest(String url) throws ClientProtocolException, IOException {
        String responseStr = null;
        //1.创建HttpGet或HttpPost对象，将要请求的URL通过构造方法传入HttpGet或HttpPost对象
        HttpGet httpGet = new HttpGet(url);
        //2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求，并返回HttpResponse对象。
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = httpclient.execute(httpGet);
        //3.通过HttpResponse接口的getEntity方法返回响应信息，并进行相应的处理。
        HttpEntity entity = httpResponse.getEntity();
        if(entity!=null){
            responseStr = EntityUtils.toString(entity);
        }
        return responseStr;
    }

    /**
     * 获取UUID
     * @return
     */
    public static String getUUID(){
        return UUID.randomUUID().toString();
    }



    /**
     * 判断字符串是否为手机号
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {

        Pattern p = Pattern.compile("^1[3|4|5|7|8][0-9]\\d{4,8}$");

        Matcher m = p.matcher(mobiles);

        return m.matches();
    }

    /**
     * 下载文件(根据流下载文件)
     * @throws Exception
     */
    public static void downloadFileFromStream(HttpServletRequest request, HttpServletResponse response, InputStream inStream, String file_name) throws Exception{
        //获得浏览器代理信息
        final String userAgent = request.getHeader("USER-AGENT");
        //判断浏览器代理并分别设置响应给浏览器的编码格式
        String finalFileName = null;
        if(StringUtils.contains(userAgent, "MSIE")|| StringUtils.contains(userAgent,"Trident")){//IE浏览器
            finalFileName = URLEncoder.encode(file_name,"UTF8");
        }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
            finalFileName = new String(file_name.getBytes(), "ISO8859-1");
        }else{
            finalFileName = URLEncoder.encode(file_name,"UTF8");//其他浏览器
        }
        //设置HTTP响应头
        response.reset();//重置 响应头
        response.setContentType("application/x-download");//告知浏览器下载文件，而不是直接打开，浏览器默认为打开
        response.addHeader("Content-Disposition" ,"attachment;filename=\"" +finalFileName+ "\"");//下载文件的名称
        // 循环取出流中的数据
        byte[] b = new byte[1024];
        int len;

        while ((len = inStream.read(b)) > 0){
            response.getOutputStream().write(b, 0, len);
        }
        inStream.close();
        response.getOutputStream().close();
    }

    /**
     * 判断一个字符串是否都为数字
     * @param strNum
     * @return
     */
    public static boolean isDigit(String strNum) {
        return strNum.matches("[0-9]{1,}");
    }

    /**
     * 判断是否为数字或小数
     * @param str
     * @return
     */
    public static boolean isNumber(String str){
        if(StringUtils.isEmpty(str)){
            return false;
        }
        String reg = "\\d+(\\.\\d+)?";
        return str.matches(reg);

    }

    /**
     * 获取客户端的ip
     * @return
     */
    public static String getIpAddr() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attrs.getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取用户IP
     * @param request
     * @return
     * @throws Exception
     */
    public static String getIp(HttpServletRequest request) throws Exception{
        String clientIp = request.getHeader("x-forwarded-for");
        if(clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("Proxy-Client-IP");
        }
        if(clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("WL-Proxy-Client-IP");
        }
        if(clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getRemoteAddr();
        }
        clientIp = clientIp.split(",")[0];
        return clientIp;
    }

    /**
     * 获取浏览器版本
     * @param request
     * @return
     * @throws Exception
     */
    public static String getBrowser(HttpServletRequest request) throws Exception {
        String browser = "";
        String browserDetails = request.getHeader("User-Agent");
        String userAgent = browserDetails;
        String user = userAgent.toLowerCase();
        if (user.contains("edge")) {
            browser = (userAgent.substring(userAgent.indexOf("Edge")).split(" ")[0]).replace("/", "-");
        } else if (user.contains("msie")) {
            String substring = userAgent.substring(userAgent.indexOf("MSIE")).split(";")[0];
            browser = substring.split(" ")[0].replace("MSIE", "IE") + "-"
                    + substring.split(" ")[1];
        } else if (user.contains("safari") && user.contains("version")) {
            browser = (userAgent.substring(userAgent.indexOf("Safari")).split(
                    " ")[0]).split("/")[0]
                    + "-"
                    + (userAgent.substring(userAgent.indexOf("Version")).split(
                    " ")[0]).split("/")[1];
        } else if (user.contains("opr") || user.contains("opera")) {
            if (user.contains("opera")) {
                browser = (userAgent.substring(userAgent.indexOf("Opera"))
                        .split(" ")[0]).split("/")[0]
                        + "-"
                        + (userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1];
            } else if (user.contains("opr")) {
                browser = ((userAgent.substring(userAgent.indexOf("OPR"))
                        .split(" ")[0]).replace("/", "-")).replace("OPR",
                        "Opera");
            }
        } else if (user.contains("chrome")) {
            browser = (userAgent.substring(userAgent.indexOf("Chrome")).split(
                    " ")[0]).replace("/", "-");
        } else if ((user.indexOf("mozilla/7.0") > -1)
                || (user.indexOf("netscape6") != -1)
                || (user.indexOf("mozilla/4.7") != -1)
                || (user.indexOf("mozilla/4.78") != -1)
                || (user.indexOf("mozilla/4.08") != -1)
                || (user.indexOf("mozilla/3") != -1)) {
            browser = "Netscape-?";

        } else if (user.contains("firefox")) {
            browser = (userAgent.substring(userAgent.indexOf("Firefox")).split(
                    " ")[0]).replace("/", "-");
        } else if (user.contains("rv")) {
            String IEVersion = (userAgent.substring(userAgent.indexOf("rv"))
                    .split(" ")[0]).replace("rv:", "-");
            browser = "IE" + IEVersion.substring(0, IEVersion.length() - 1);
        } else {
            browser = "UnKnown, More-Info: " + userAgent;
        }
        return browser;
    }

}
